// 菜单路由设置
// 通过后台动态加载菜单，并提供给vue-router做成路由

import httpAPI from '../utils/httpapi'
import {Message} from 'element-ui'

//保证路由是从斜杠开始的
const joinRoutes = (subDirs) =>{
  let ret = "";

  for (let i = 0; i < subDirs.length; i++) {
    ret += "/";
    ret += subDirs[i];
  }
  
  return ret;
}

// 初始化菜单的跳转路径
const initRouter = (router, store) => {
  // 如果store中已有，则说明路由配置过了
  if (store.state.routes.length > 0) 
    return;
  // 获取路由配置 /static/data/routes.json /sysVuelyxxb/menu 
  httpAPI.getRequest("/static/data/routes.json", {
    jsbh:store.state.user.role
  }).then(resp => {
    if (resp && resp.status == 200) {
      if(resp.data.success){
        var fmtRoutes = formatRoutes(resp.data.routes);// 把路由格式化好
        store.commit("initRouter", fmtRoutes); //改变全局状态
        router.addRoutes(fmtRoutes); // 添加新的路由
      }else{
        Message.error("请求页面出错，错误原因:" + resp.data.msg);
      }
    }
  });
}

// 格式化菜单项的路由
// 注意：这里有一个 嵌套菜单和嵌套路由一致处理。也就是路由是什么样的嵌套，菜单就怎么组织
const formatRoutes = (routes, parentPath) => {
  let fmRoutes = [];
  routes.forEach(router => {
    let {
      code,
      name,
      alias,
      description,
      iconCls,
      path,
      component,
      meta,
      children
    } = router;

    let subDirs = path.split("/");//去掉第一个(一定是空字符串)，去掉最后一个(一定是组件)
    let modulePath = parentPath?(parentPath + path):(path);
    // console.log("modulePath=",modulePath);
    if ((children) && (children instanceof Array) && (children.length > 0)) {
      children = formatRoutes(children, joinRoutes(subDirs.slice(1,-1)));// 递归处理子菜单
    }else{
      children = null;
    }
    
    // 这里构建的是新的路由route配置项，参数配置见https://router.vuejs.org/zh-cn/api/options.html#routes
    let fmRouter = {
      path: path,
      component: function(resolve) {
        // 异步方式加载模块，这是vue的异步组件写法
        // 同时根据文件夹深度不同，进行不同的处理
        require(['../modules' + modulePath + '.vue'], resolve);

      },
      name: name,
      alias: alias,
      description: description,
      iconCls: iconCls,
      meta: meta,
      children: children
    };
    fmRoutes.push(fmRouter);
  })
  return fmRoutes;
}

export default initRouter;
